<template>
    <el-form :model="selectDate" style="margin: 20px 40px; display: flex;" v-if="IdentityType === 0">
        <el-form-item label="选择查看报告的学期" style="margin-right: 20px;">
            <el-select v-model="selectDate.YearTream" placeholder="您要查看那个学期的报告?">
                <el-option v-for="item in YearTreamList" :label="item" :value="item" />
            </el-select>
        </el-form-item>
        <el-form-item>
            <el-button type="primary" @click="selectSumbitTrem()"><el-icon>
                    <Search />
                </el-icon>搜索</el-button>
        </el-form-item>
    </el-form>
    <div class="common-layout" v-if="IdentityType === 1">
        <h1>教师端专用功能</h1>
    </div>
    <div class="common-layout" v-if="showDiv">
        <el-container>
            <el-header>
                <h1>班级的五育发展情况概览</h1>
            </el-header>
            <el-main>
                <!--整体情况说明 -->
                <div class="total">
                    <h2>【整体情况】</h2>
                    <div class="part1">
                        <h3>➢说明 : </h3>
                        <p>✧ 这一部分通过班级各月的综合评价分数反映班级五育发展的整体情况，<span
                                style="font-weight:800">呈现的结果可能受到教师评价侧重存在问题等因素的干扰。</span></p>
                        <p>✧
                            一个班级的综合评价分数，是根据该班级所有学生的综合评价情况计算得到的平均值，并根据该平均值给出分数评定，该分数越高，表明综合评价越高。学生的综合评价情况是根据该学生在德育、智育、体育、美育、劳育这五个方面的得分情况综合计算得到的。综合评价分数展示的是五育发展的整体性情况。
                        </p>
                        <div>
                            <p>✧ 图表I展现的是本班级的综合评价情况在所有班级中所在的具体位置。</p>
                            <p style="margin-left: 20px;">✔ 图中的矩形越长，表明本班级的相对位置越高，即排名越靠前。</p>
                            <p style="margin-left: 20px;">✔ {{ TotalAnalyse1 }}</p>
                            <p style="margin-left: 20px;">✔ 图中的矩形用不同颜色填充，以区分不同月份的评价情况。</p>
                        </div>
                        <div class="imageToal1">
                            <div id="image-1" style="width: 100%;"></div>
                            <p>图表I 班级的综合评价情况</p>
                        </div>
                        <p>✧ 图表II展示了本班级的综合评价按标准九分的方式评定，得到的各月分数以及该学期整体分数的情况。</p>
                        <div class="imageToal2">
                            <el-table :data="[tableData_total]" border>
                                <el-table-column v-for="(item, index) in months" :key="index" :label="item"
                                    :prop="item"></el-table-column>
                            </el-table>
                            <p>图表II 各月的综合评价情况(单位为分)</p>
                        </div>
                    </div>
                    <div class="part2">
                        <h3>➢分析 : </h3>
                        <p>✧ {{ TotalAnalyse2 }}</p>
                        <p>✧ {{ TotalAnalyse3 }}</p>
                    </div>
                </div>
                <!-- 分割线 -->
                <div class="divider"></div>
                <div class="spare">
                    <h2>【均衡情况】</h2>
                    <div class="part1">
                        <h3>➢说明 : </h3>
                        <div>
                            <p>✧ 图表III表示的是本班级在五育分项评价的各个方面的情况。</p>
                            <p style="margin-left: 20px;">✔ 图中的各个五边形的形状展现的是班级五育发展的均衡程度。图中的五边形越接近于正五边形，表明该班级五育发展越均衡。</p>
                            <p style="margin-left: 20px;">✔
                                图中既包括了各个月份的五育分项评价情况，也包括了该学期整体的五育分析评价情况，并用不同颜色、不同线型对各个月份的五育评价情况加以区分。</p>
                            <p style="margin-left: 20px;">✔ 图中的五边形的某一顶点越接近图中的边缘位置，表明该班级在该项上的相对位置越高，即排名越靠前。</p>
                        </div>
                        <p>✧ 一个班级的五育分项评价是基于该班级所有学生在某一项上的分数计算得到的平均值，并根据该平均值给出分数评定。某一项的分数越高，表明在该项上的评价越高。</p>
                        <div class="imageToal3">
                            <div id="image-3"></div>
                            <p>图表III 班级五育分项评价情况雷达图</p>
                        </div>
                        <div class="imageToal4">
                            <el-table :data="formattedData" border style="width: 100%">
                                <el-table-column prop="time" label="日期" />
                                <el-table-column prop="德育" label="德育" />
                                <el-table-column prop="智育" label="智育" />
                                <el-table-column prop="体育" label="体育" />
                                <el-table-column prop="美育" label="美育" />
                                <el-table-column prop="劳育" label="劳育" />
                            </el-table>
                            <p>图表IV 各月的五育分项评价情况</p>
                        </div>
                    </div>
                    <div class="part2">
                        <h3>➢分析 : </h3>
                        <p>✧ {{ EquilibriumAnalyse1 }}</p>
                        <p v-if="EquilibriumAnalyse2">✧ {{ EquilibriumAnalyse2 }}</p>
                        <p>✧ {{ EquilibriumAnalyse3 }}</p>
                        <p>✧ {{ EquilibriumAnalyse4 }}</p>
                    </div>
                </div>
            </el-main>
        </el-container>
    </div>
</template>

<script setup>
/* 引入依赖  */
import { ref, onMounted } from 'vue';
import * as echarts from 'echarts';
import { toRefs } from '@vueuse/core';
/* 引入self的js */
import useTeacherInfo from "@/api/classReport/index";
const { scoreList, loadData, userInfo } = useTeacherInfo();

// 是否显示页面信息
const showDiv = ref(false);
// 教师 ? 管理员
const IdentityType = ref(0);
const YearTreamList = ref([]);
// 选择数据
const selectDate = ref({
    YearTream: ''
})
// 原始分数数据 
const ClassScore = ref([]);
// 处理之后的分数数据
const handleDate = ref([])
// 图标的颜色数据
const color = ref([
    '#D7B3A6',
    '#B17A6B',
    '#B7D7A8',
    '#A3C4D1',
    '#F6A5B3',
    '#E28D6D',
    '#C8A3C5',
    '#F4D97F',
    '#E6C76B',
    '#B1C5A9',
    '#E0A6C2',
    '#F7B7A3',
    '#A6C6D5'
]);
/* 格式为2024-09 */
const Year_Months = ref([]);
// 定义月份和对应的分数数据 --整体的表格信息 格式为8月..
const months = ref([]);
const tableData_total = ref({});
// 均衡的表格信息
const spareDate = ref([])
// 均衡的表格信息的数据处理
const formattedData = computed(() =>
    spareDate.value.map(item => ({
        time: item.time,
        德育: item.value[0],
        智育: item.value[1],
        体育: item.value[2],
        美育: item.value[3],
        劳育: item.value[4]
    }))
);
// 条形图
const TxtDate = reactive({
    yDate: [],
    xDate: []
})
const { yDate, xDate } = toRefs(TxtDate)
function createImage1() {
    // 基于准备好的dom，初始化echarts实例
    var myChart = echarts.init(document.getElementById('image-1'));
    myChart.setOption({
        yAxis: {
            type: 'category',
            data: yDate.value,
            axisLine: { show: false },
            axisTick: { show: false },
        },
        xAxis: {
            type: 'value',
            min: 0,
            max: 9,
            axisLine: { show: false },
            axisTick: { show: true },
            axisLabel: {
                show: true,
                interval: 0
            },
            splitLine: {
                show: true,
                lineStyle: {
                    type: 'dashed',
                    color: '#999'
                }
            },
            splitNumber: 9
        },
        series: [
            {
                data: xDate.value,
                type: 'bar',
                itemStyle: {
                    color: function (params) {
                        const colors = color.value;
                        return colors[params.dataIndex];
                    }
                }
            }
        ]
    });
}
// 雷达图数据
const LdtDate = reactive({
    Ldtdata: [],
    LdtList: []
})
const { Ldtdata, LdtList } = toRefs(LdtDate)
function createImage3() {
    // 基于准备好的dom，初始化echarts实例
    var myChart = echarts.init(document.getElementById('image-3'));
    const data = Ldtdata.value
    const list = LdtList.value
    const option = {
        color: color.value,
        legend: {
            data: data
        },
        radar: {
            indicator: [
                { name: '德育', max: 9 },
                { name: '智育', max: 9 },
                { name: '体育', max: 9 },
                { name: '美劳', max: 9 },
                { name: '劳育', max: 9 }
            ]
        },
        series: [
            {
                name: 'Budget vs spending',
                type: 'radar',
                data: list.map(item => ({
                    value: item.value,
                    name: item.name
                }))
            }
        ]
    };
    myChart.setOption(option);
}
// 处理数据
function HandleDate() {
    // 月份
    var List = ref([])
    ClassScore.value.sort((a, b) => {
        const dateA = new Date(a.month);
        const dateB = new Date(b.month);
        return dateA - dateB;
    });
    ClassScore.value.forEach(item => {
        Year_Months.value.push(item.month.substring(0, 7));
        List.value.push({
            month: `${parseInt(item.month.split('-')[1], 10)}月`,
            strandScore: JSON.parse(item.strandScore)
        })
    })
    // 拿取五育成绩和总和成绩 处理list列表
    List.value.forEach(item => {
        const strandScore = item.strandScore;
        handleDate.value.push({
            month: item.month,
            scoreList: [strandScore['1'], strandScore['2'], strandScore['3'], strandScore['4'], strandScore['5']],
            strandScore: strandScore['totalIndicator']
        })
    })
    // console.log("月份", months.value);
    // console.log("成绩数据", handleDate.value);
    assignmentData()
}
// 给数组赋值
function assignmentData() {
    var totalscore = 0;
    var spareList = ref([
        { value: 0 },
        { value: 0 },
        { value: 0 },
        { value: 0 },
        { value: 0 }
    ]); // 初始化为5个包含value字段的对象
    handleDate.value.forEach(item => {
        // 综合评价之表格
        months.value.push(item.month);
        tableData_total.value[item.month] = item.strandScore;
        totalscore += item.strandScore;

        // 综合评价之条形
        xDate.value.push(item.strandScore);
        yDate.value.push(item.month);

        // 均衡评价之表格
        spareDate.value.push({
            time: item.month,
            value: item.scoreList
        });

        // 累加均衡评分
        spareList.value.forEach((spare, index) => {
            spare.value += item.scoreList[index];
        });

        // 均衡评价之雷达图
        LdtList.value.push({
            name: item.month,
            value: item.scoreList
        });
        Ldtdata.value.push(item.month);
    });

    // 添加该学期整体评价信息
    months.value.push("该学期整体评价");
    tableData_total.value["该学期整体评价"] = Math.round(totalscore / handleDate.value.length);

    // 添加均衡信息的总学期评价
    const semesterAvgScore = Math.round(totalscore / handleDate.value.length);
    xDate.value.push(semesterAvgScore);
    yDate.value.push('学期评价');

    // 均衡评价
    spareDate.value.push({
        time: "学期评价",
        value: spareList.value.map(spare => Math.round(spare.value / handleDate.value.length)) // 提取每个value作为值
    });

    LdtList.value.push({
        name: "学期评价",
        value: spareList.value.map(spare => Math.round(spare.value / handleDate.value.length)) // 提取每个value作为值
    });

    Ldtdata.value.push("学期评价");
}

// 获取模板信息
import { listPerformancecomparisons } from '@/api/performancecomparisons/performancecomparisons'
const Template = ref([])
// 具体的模板信息
const Equilibrium_judgement = ref('')
const Standard_Nine_Division = ref('')
const Number_of_grades = ref('')
const Floating_standard = ref('')
function getTemplate() {
    listPerformancecomparisons().then(res => {
        // console.log(res);
        if (res.code == 200) {
            Template.value = res.rows
            Template.value.forEach(item => {
                if (item.type == 'Equilibrium_judgement') Equilibrium_judgement.value = item.scoreRanges
                if (item.type == 'Standard_Nine_Division') Standard_Nine_Division.value = item.scoreRanges
                if (item.type == 'Number_of_grades') Number_of_grades.value = item.scoreRanges
                if (item.type == 'Floating_standard') Floating_standard.value = item.scoreRanges
            })
            setText()
            generateBalancedEvaluation()
        }
    })
}
// 文本信息
const text = reactive({
    TotalAnalyse1: "TotalAnalyse1",
    TotalAnalyse2: "TotalAnalyse2",
    TotalAnalyse3: "TotalAnalyse3",
    EquilibriumAnalyse1: "EquilibriumAnalyse1",
    EquilibriumAnalyse2: "EquilibriumAnalyse2",
    EquilibriumAnalyse3: "EquilibriumAnalyse3",
    EquilibriumAnalyse4: "EquilibriumAnalyse4",
})
const { TotalAnalyse1, TotalAnalyse2, TotalAnalyse3, EquilibriumAnalyse1, EquilibriumAnalyse2, EquilibriumAnalyse3, EquilibriumAnalyse4 } = toRefs(text)
// 给文本信息赋值
function setText() {
    // 1.综合评价说明
    TotalAnalyse1.value = `图中既包括了本班级于${Year_Months.value[0]}月到${Year_Months.value[Year_Months.value.length - 1]}月之间的综合评价，也显示了该班级在各不同月份的综合评价情况，也包括了该学期整体的综合评价情况。`
    // 2.综合评价分析
    // 2.1 查找分数最大最小值将 tableData_total 转换为数组并排除最后一个元素
    const scoresArray = Object.entries(tableData_total.value)
        .slice(0, -1) // 排除最后一个值
        .map(([month, score]) => ({
            month,
            score
        }));
    // 确保 scoresArray 是数组且不为空
    var maxScore = 0
    var minScore = 0
    var maxScoreData = []
    var minScoreData = []
    if (Array.isArray(scoresArray) && scoresArray.length > 0) {
        // 找到最高分和最低分的分数值
        maxScore = Math.max(...scoresArray.map(item => item.score));
        minScore = Math.min(...scoresArray.map(item => item.score));
        // 筛选出所有最高分的月份
        maxScoreData = scoresArray.filter(item => item.score === maxScore);
        // 筛选出所有最低分的月份
        minScoreData = scoresArray.filter(item => item.score === minScore);
        // console.log("最高分数:", maxScore, "对应的月份:", maxScoreData.map(item => item.month));
        // console.log("最低分数:", minScore, "对应的月份:", minScoreData.map(item => item.month));
    } else {
        console.log("tableData_total.value 不是有效的分数数据数组");
    }
    var descriptionList = []
    scoresArray.forEach(item => {
        const description = getScoreDescription(item.score, Standard_Nine_Division)
        descriptionList.push({
            time: item.month,
            description: description
        })
    })
    console.log(descriptionList);
    
    TotalAnalyse2.value = 
    `${Year_Months.value[0]}月到${Year_Months.value[Year_Months.value.length - 1]}月期间,${generateEvaluationSummary(descriptionList)}在这段评价时间内，
${maxScoreData.map(item => item.month)}综合评价分数最高，为${maxScore}分，表现最佳；${minScoreData.map(item => item.month)}的综合评价分数最低，为${minScore}分,表现的最不理想；该学期整体的综合评价分数为${tableData_total.value["该学期整体评价"]}`

    TotalAnalyse3.value = `${Year_Months.value[0]}月到${Year_Months.value[Year_Months.value.length - 1]}月期间,${generateTrendDescription(scoresArray)}本班级的综合评价分数始终在${tableData_total.value["该学期整体评价"]}分上下。`

    // 均衡信息文本-1
    EquilibriumAnalyse1.value = generateBalancedEvaluation()
    // 均衡信息文本-4
    EquilibriumAnalyse4.value = BanlanceAnalysis()
    // 均衡信息文本-3
    EquilibriumAnalyse3.value = strengthAndWeaknessesAnalyse()[0]
    // 均衡信息文本-2
    if (strengthAndWeaknessesAnalyse()[1]) {
        EquilibriumAnalyse2.value = `在各月表现中，${strengthAndWeaknessesAnalyse()[1]}`
    } else {
        EquilibriumAnalyse2.value = ""
    }
}
/** 
 * 生成均衡评价
 * 1. 德智体美劳一级指标所在区间的描述,如果在这个描述区间里面的个数大于Number_of_grades的值,则说明这个是主要区间
 * 2. 一个月的月份下的指标完全大于或者小于别的月份时候才输出这个月
 * @returns
 */
function generateBalancedEvaluation() {
    const formattedData = spareDate.value
        .map(item => ({
            time: item.time,
            德育: item.value[0],
            智育: item.value[1],
            体育: item.value[2],
            美育: item.value[3],
            劳育: item.value[4]
        }))
        .slice(0, -1);  // 去除最后一个元素
    let summary = '';

    // 统计每个月五育各分项的得分描述信息（区间）
    const monthDescriptions = formattedData.map(item => {
        return {
            德育: getScoreDescription(item.德育, Standard_Nine_Division),
            智育: getScoreDescription(item.智育, Standard_Nine_Division),
            体育: getScoreDescription(item.体育, Standard_Nine_Division),
            美育: getScoreDescription(item.美育, Standard_Nine_Division),
            劳育: getScoreDescription(item.劳育, Standard_Nine_Division),
        };
    });

    // console.log(monthDescriptions);
    // 统计描述信息出现的次数
    const descriptionCounts = {};
    monthDescriptions.forEach(item => {
        Object.values(item).forEach(description => {
            descriptionCounts[description] = (descriptionCounts[description] || 0) + 1;
        });
    });

    // console.log(descriptionCounts);

    // 判断是否有一个区间占据主导地位
    const maxDescription = Object.entries(descriptionCounts).reduce((max, current) =>
        current[1] > max[1] ? current : max
    );

    // 如果不同区间的个数大于4，考虑集中在多个区间
    const uniqueDescriptions = Object.keys(descriptionCounts);
    const descriptionThreshold = Number_of_grades.value;  // 可以根据需要调整此阈值

    // 判断是否集中在某些区间
    if (uniqueDescriptions.length <= descriptionThreshold) {
        summary += `本班级于${Year_Months.value[0]}月到${Year_Months.value[Year_Months.value.length - 1]}月这段时间内的五育评价结果显示，本班级的五育各个分项在这${formattedData.length}个月内，基本都保持在${maxDescription[0]}这一区间内。`;
    } else {
        summary += `本班级的五育各个分项在这${formattedData.length}个月内，涵盖了多个区间，包括${Object.keys(descriptionCounts).join('、')}等区间。`;
    }

    // 找出表现最好的和最差的月份
    const bestMonth = getBestMonth(formattedData);
    const worstMonth = getWorstMonth(formattedData);

    const bestMontht = bestMonth ? bestMonth.time : '';
    const worstMontht = worstMonth ? worstMonth.time : '';
    if (bestMontht) summary += `其中，${bestMonth.time}的表现最佳，所有的分项评价均高于其他月份的相应分项评价；`;
    if (worstMontht) summary += `${worstMonth.time}的表现最不理想，所有的分项评价均低于其他月份的相应分项评价。`;
    return summary;
}

/**
 * 五育发展是否均衡分析-文本分析4
 * 班级的五育发展是否均衡，如果某一项最大值与最小值的标准九段差值大于等于gap为浮动大，则输出浮动大，否则输出平衡。
 */
function BanlanceAnalysis() {
    // 某一项最大值与最小值的标准九段差值大于等于gap为浮动大
    const gap = parseInt(Floating_standard.value)
    const formattedData = spareDate.value
        .map(item => ({
            time: item.time,
            德育: item.value[0],
            智育: item.value[1],
            体育: item.value[2],
            美育: item.value[3],
            劳育: item.value[4]
        }))
        .slice(0, -1);  // 去除最后一个元素
    const subjects = ["德育", "智育", "体育", "美育", "劳育"];
    // 存储每个指标下的最大最小值
    const result = {
        subjectsMaxMin: {},  // 每个分项的最大值和最小值
        overallMax: { score: -Infinity, subject: '', month: '' },
        overallMin: { score: Infinity, subject: '', month: '' }
    };

    subjects.forEach(subject => {
        let maxScore = -Infinity;
        let minScore = Infinity;
        let maxMonth = '';
        let minMonth = '';
        formattedData.forEach(item => {
            if (item[subject] > maxScore) {
                maxScore = item[subject];
                maxMonth = item.time;
            }
            if (item[subject] < minScore) {
                minScore = item[subject];
                minMonth = item.time;
            }

            if (item[subject] > result.overallMax.score) {
                result.overallMax = { score: item[subject], subject: subject, month: item.time };
            }
            if (item[subject] < result.overallMin.score) {
                result.overallMin = { score: item[subject], subject: subject, month: item.time };
            }
        });
        result.subjectsMaxMin[subject] = {
            max: { score: maxScore, month: maxMonth },
            min: { score: minScore, month: minMonth }
        };
    });

    let summary = ''
    const distance = getScoreDescription((result.overallMax.score - result.overallMin.score), Equilibrium_judgement)
    summary += `整体上看，图表III呈现的五育各分项之间${distance}，教师在维持本班级${result.overallMax.subject}发展优势的同时,也要注意本班级学生的${result.overallMin.subject}表现。`

    const float = []
    Object.keys(result.subjectsMaxMin).forEach(item => {
        const dis = result.subjectsMaxMin[item].max.score - result.subjectsMaxMin[item].min.score
        if (dis >= gap) float.push(item)
    })

    if (float.length > 0) {
        summary += `此外，在${float.join('、')}方面，有${float.length}项出现了大幅波动，这一大幅度的变化也值得教师的注意。`
    }
    return summary;

}
/**
 * 找出表现最好的和最差的月份
 */
function getBestMonth(formattedData) {
    let bestMonth = null;
    for (let i = 0; i < formattedData.length; i++) {
        const currentMonth = formattedData[i];
        const isBetter = formattedData.every((otherMonth, j) => {
            if (i === j) return true; // 跳过自身比较
            return Object.keys(currentMonth).slice(1).every(subject => currentMonth[subject] > otherMonth[subject]);
        });
        if (isBetter) {
            bestMonth = currentMonth;
            break; // 找到最佳月份后立即退出
        }
    }
    return bestMonth;
}

// 找出表现最差的月份
function getWorstMonth(formattedData) {
    let worstMonth = null;
    for (let i = 0; i < formattedData.length; i++) {
        const currentMonth = formattedData[i];
        const isWorse = formattedData.every((otherMonth, j) => {
            if (i === j) return true; // 跳过自身比较
            return Object.keys(currentMonth).slice(1).every(subject => currentMonth[subject] < otherMonth[subject]);
        });
        if (isWorse) {
            worstMonth = currentMonth;
            break; // 找到最差月份后立即退出
        }
    }
    return worstMonth;
}

// 整体评价趋势变化
function generateTrendDescription(scoresArray) {
    let trend = [];  // 用于存储每个月的变化趋势
    let description = '';

    // 判断相邻月份的评分变化
    for (let i = 1; i < scoresArray.length; i++) {
        const prevScore = scoresArray[i - 1].score;
        const currentScore = scoresArray[i].score;

        if (currentScore > prevScore) {
            trend.push('上升');
        } else if (currentScore < prevScore) {
            trend.push('下降');
        } else {
            trend.push('平稳');
        }
    }

    // 判断变化趋势：是否存在“先下降，后上升，再平稳”的趋势
    let hasDescended = false;  // 是否经历过下降
    let hasAscended = false;   // 是否经历过上升
    let hasStayed = false;     // 是否经历过平稳

    trend.forEach(change => {
        if (change === '下降') hasDescended = true;
        if (change === '上升') hasAscended = true;
        if (change === '平稳') hasStayed = true;
    });

    // 根据变化趋势生成描述
    if (hasDescended && hasAscended && hasStayed) {
        description = '整体呈现出先明显下降，后小幅度上升，最后保持平稳的趋势。';
    } else if (hasDescended && hasAscended) {
        description = '整体呈现出先明显下降，后小幅度上升的趋势。';
    } else if (hasAscended) {
        description = '整体呈现出上升的趋势。';
    } else if (hasDescended) {
        description = '整体呈现出下降的趋势。';
    } else if (hasStayed) {
        description = '整体保持平稳。';
    }

    return description;
}
// 生成综合评价文本
function generateEvaluationSummary(data) {
    console.log(data);
    
    const x = parseInt(Number_of_grades.value)
    // 首先提取所有描述信息
    const descriptions = data.map(item => item.description);

    // 获取去重后的描述集合
    const uniqueDescriptions = [...new Set(descriptions)];

    // 统计每个描述的出现次数
    const descriptionCounts = uniqueDescriptions.map(description => {
        return {
            description,
            months: data.filter(item => item.description === description).map(item => item.time)
        };
    });

    // 结果初始化
    let summary = '';

    if (descriptionCounts.length <= x) {
        // 如果不同描述的个数小于等于x，则输出一个整体描述
        summary = `本班级的综合评价始终保持在${descriptionCounts[0].description}区间内。`;
    } else {
        // 如果不同描述的个数大于x，则按照每个描述输出相同等级的月份
        descriptionCounts.forEach(item => {
            const months = item.months.join("、");
            summary += `${months}期间，本班级的综合评价始终保持在${item.description}区间内。\n`;
        });
    }

    return summary;
}

// 判断一个分数属于哪个区间
function getScoreDescription(score, strand) {
    const scoreRanges = JSON.parse(strand.value)
    for (let range of scoreRanges) {
        if (score >= range.start && score <= range.end) {
            return range.description;
        }
    }
    return null; // 如果分数不在任何区间内
}

/**
 * 强项弱势项分析
 */
const StrengthsAndWeaknesses = {
    StrengthsAndWeaknessesDate: []
}
const { StrengthsAndWeaknessesDate } = toRefs(StrengthsAndWeaknesses)
function strengthAndWeaknessesAnalyse() {
    // 处理一下数据
    var data = []
    StrengthsAndWeaknessesDate.value.forEach(item => {
        const strandScore = JSON.parse(item.strandScore)
        const transformScore = JSON.parse(item.transformScore)
        data.push({
            month: item.month,
            strandScore: [strandScore['1'], strandScore['2'], strandScore['3'], strandScore['4'], strandScore['5'], strandScore['totalIndicator']],
            transformScore: [transformScore['1'], transformScore['2'], transformScore['3'], transformScore['4'], transformScore['5'], transformScore[1]]
        })
    })

    // 开始比较
    const analysisResults = [];
    const advantagesCount = [0, 0, 0, 0, 0];
    const weaknessesCount = [0, 0, 0, 0, 0];
    data.forEach(item => {
        // 获取总的转化分数（最后一个是总分）
        const totalTransformScore = item.transformScore[5];
        const totalStrandScore = item.strandScore[5];

        // 存储每个月的优势项和弱势项
        const monthAnalysis = {
            month: item.month,
            advantages: [],  // 优势项
            weaknesses: [],  // 弱势项
        };

        // 遍历每个一级指标并进行判断
        item.transformScore.slice(0, 5).forEach((transform, index) => {
            const strand = item.strandScore[index];

            // 判断是否为弱势项 一级指标的转化分数小于总分的转化分数，且对应的一级指标的标准九段小于总分的标准九段
            if (transform < totalTransformScore && strand < totalStrandScore) {
                var s = getIndicatorName(index + 1)
                monthAnalysis.weaknesses.push(`${s}`);
                advantagesCount[index]++;
            }
            // 判断是否为优势项 一级指标的转化分数大于总分的转化分数
            else if (transform > totalTransformScore) {
                var s = getIndicatorName(index + 1)
                monthAnalysis.advantages.push(`${s}`);
                weaknessesCount[index]++;
            }
        });

        // 将分析结果添加到结果数组中
        analysisResults.push(monthAnalysis);
    });

    let summary = '具体来看，'

    analysisResults.forEach(item => {
        if (item.advantages.length > 0 && item.weaknesses.length > 0) {
            summary += `${item.month}月，该班级的${item.advantages.join("、")}项是优势项，${item.weaknesses.join("、")}项是弱势项。`
        } else if (item.advantages.length == 0 && item.weaknesses.length > 0) {
            summary += `${item.month}月，该班级的无优势项 , ${item.weaknesses.join("、")}项是弱势项。`
        } else if (item.advantages.length > 0 && item.weaknesses.length == 0) {
            summary += `${item.month}月，该班级的${item.advantages.join("、")}项是优势项 , 无弱势项。`
        }
    })

    let summary1 = ''
    const count = StrengthsAndWeaknessesDate.value.length
    advantagesCount.forEach((item, index) => {
        if (item == count) {
            summary1 += `${getIndicatorName(index + 1)}始终是本班级的优势项，且相对稳定； `
        }
    });
    weaknessesCount.forEach((item, index) => {
        if (item == count) {
            summary1 += `${getIndicatorName(index + 1)}始终是本班级的弱势项； `
        }
    });
    // console.log(advantagesCount);
    // console.log(weaknessesCount);

    return [summary, summary1]
}

// 判断指标名称
function getIndicatorName(indicatorId) {
    var indicatorName = ''
    switch (indicatorId) {
        case 1: indicatorName = '德育'; break;
        case 2: indicatorName = '智育'; break;
        case 3: indicatorName = '体育'; break;
        case 4: indicatorName = '劳育'; break;
        case 5: indicatorName = '美育'; break;
    }
    return indicatorName
}

// 判断选择哪个学期
function getGenTrem() {
    const List = getSemesterNames(userInfo.workList.yearAdmission)
    List.forEach(item => {
        YearTreamList.value.push(item)
    })
}

function getSemesterNames(admissionYear) {
    const currentYear = new Date().getFullYear();
    const currentMonth = new Date().getMonth() + 1;
    let semesterNames = [];

    // 计算入学到当前学期的总学期数
    let totalSemesters = (currentYear - admissionYear) * 2 + (currentMonth >= 9 || currentMonth === 0 ? 1 : 0);

    // 遍历每个学期，生成学期名称
    for (let i = 0; i < totalSemesters; i++) {
        let grade = Math.floor(i / 2) + 1;  // 年级，i / 2 向下取整
        let semester = i % 2 === 0 ? '上学期' : '下学期';  // 奇偶学期判断

        // 生成学期名称并加入数组
        semesterNames.push(`${grade}年级${semester}`);
    }

    return semesterNames;
};

async function getTermDates(startYear, gradeTerm) {
    // 解析学年和学期
    const regex = /(\d+)年级(上学期|下学期)/;
    const match = gradeTerm.match(regex);

    if (!match) {
        return null; // 格式错误
    }

    const grade = parseInt(match[1]); // 获取年级
    const term = match[2]; // 获取学期（上学期或下学期）
    // 根据入学年份和年级推算当前学年的年份
    const schoolYear = startYear + grade - 1; // 学年从入学年份开始

    let startMonth, endMonth;

    // 根据学期推算起始和结束月份
    if (term === "上学期") {
        // 上学期：从 9月 到 1月
        startMonth = 9;
        endMonth = 1; // 上学期通常到第二年1月结束
    } else if (term === "下学期") {
        // 下学期：从 3月 到 6月
        startMonth = 3;
        endMonth = 6;
    }

    const startDateYear = startMonth === 9 ? schoolYear : schoolYear + 1; // 上学期年份不变，下学期年份加 1
    const endDateYear = endMonth === 1 ? schoolYear + 1 : schoolYear; // 上学期结束在第二年，下学期保持当前年份

    // 拼接日期，确保月份为两位数
    const startDate = `${startDateYear}-${String(startMonth).padStart(2, '0')}`;
    const endDate = `${endDateYear}-${String(endMonth).padStart(2, '0')}`;

    return {
        startDate,
        endDate
    };
};
async function selectSumbitTrem() {
    const trem = selectDate.value.YearTream
    const yearAdmission = userInfo.workList.yearAdmission
    showDiv.value = true
    const result = await getTermDates(parseInt(yearAdmission), trem);
    const data = ClassScore.value
    const temp = []
    data.forEach(item => {
        if(item.month >= result.startDate && item.month <= result.endDate){
            temp.push(item)
        }
    });
    console.log(temp);
    
    ClassScore.value = temp
    StrengthsAndWeaknessesDate.value = temp
    console.log(ClassScore.value);
    
    HandleDate()
    createImage1()
    createImage3()
    getTemplate()
};
// 使用 loadData 确保数据加载完成后再打印
onMounted(async () => {
    try {
        await loadData()  // 等待数据加载完成
        const data = scoreList._rawValue
        if (data.length) IdentityType.value = 0
        else IdentityType.value = 1
        ClassScore.value = data
        StrengthsAndWeaknessesDate.value = data
        getGenTrem()
    } catch (error) {
        // console.log(error);
    }
});
</script>

<style scoped>
.common-layout {
    padding: 10px;
    width: 100%;
}

.el-header {
    text-align: center;
    font-size: 20px;
    font-weight: 900;
}

.el-main {
    display: flex;
    justify-content: space-between;
    width: 100%;
}

.total,
.spare {
    width: 49%;
    text-align: left;
    padding: 10px;
}

.divider {
    width: 1px;
    /* 设置分割线的宽度 */
    border-left: 1px dashed #ccc;
    /* 设置为竖直虚线 */
    margin: 0 10px;
    /* 设置左右间距 */
}

.imageToal1 {
    display: flex;
    flex-direction: column;
}


.imageToal1 div {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    text-align: center;
    height: 400px;
}

.imageToal1 p {
    text-align: center;
    margin-top: -30px;
}

.imageToal2 p {
    text-align: center;
}

.el-table-column {
    font-weight: bold;
    text-align: center;
}

.el-table td {
    padding: 4px;
}

/**均衡情况**/
.imageToal3 {
    display: flex;
    flex-direction: column;
}

.imageToal3 div {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    text-align: center;
    height: 400px;
}

.imageToal3 p {
    text-align: center;
    margin-top: -30px;
}

.imageToal4 {
    display: flex;
    flex-direction: column;
}

.imageToal4 div {
    display: flex;
    flex-direction: column;
    justify-content: center;
    text-align: center;
}

.imageToal4 p {
    text-align: center;
}
</style>
